#pragma once
#include <string>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <unistd.h>
#include <memory>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>
#include "Log.hpp"


class Sock{
private:
    const static int gbacklog = 20;
public:
    Sock() {}
    int Socket()
    {
        int listensock =socket(AF_INET,SOCK_STREAM,0);//创建套接字
        if(listensock<0)
        {
            logMessage(FATAL, "create socket error, %d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(DEBUG,"create socket right,%d",listensock);
        return listensock;
    }
    void Bind(const int sock,const uint16_t port,std::string ip="0.0.0.0")
    {
        struct sockaddr_in  local;
        memset(&local, 0, sizeof local);
        local.sin_family=AF_INET;//协议家族
        local.sin_port=htons(port);//主机转网络
        inet_pton(AF_INET, ip.c_str(), &local.sin_addr);//将网络文本转化为二进制形式
        if(bind(sock,(struct sockaddr*)&local,sizeof local)<0)
        {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(3);
        }
    }

    void Listen(int sock)//监听
    {
        if(listen(sock,gbacklog)<0)
        {
            logMessage(FATAL,"listen error,%d,%s",errno,strerror(errno));
            exit(3);
        }
        logMessage(DEBUG,"init server success");
    }
    // 一般经验
    // const std::string &: 输入型参数
    // std::string *: 输出型参数
    // std::string &: 输入输出型参数
    int Accept(const int sock,uint16_t* port,std::string* ip,int* accept_errno=0)//接收
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int serversock=accept(sock,(struct sockaddr*)&src,&len);
        if(serversock<0)
        {
            *accept_errno=errno;
            exit(1);
        }
        if(port) *port = ntohs(src.sin_port);//网络转主机
        if(ip) *ip = inet_ntoa(src.sin_addr);
        return serversock;//返回
    }
    bool Connect(int sock,const std::string &server_ip, const uint16_t &server_port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(server_port);
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());

        if(connect(sock,(struct sockaddr*)&server, sizeof(server)) == 0) return true;
        else return false;
    }
    ~Sock()
    {
        ;
    }

    bool SetNonBlock(int sock)
    {
        int f1=fcntl(sock,F_GETFL);
        if(f1<0) return false;
        fcntl(sock, F_SETFL, f1 | O_NONBLOCK);
        return true;
    }
};
